package cn.edu.scut.suggestion;

/**
 * 在模块度算法的结果基础上，进行短语扩展
 * @author tian.yuchen
 */

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import cn.edu.scut.hsrc.bean.CandidatePhrase;
import cn.edu.scut.hsrc.bean.Doc;
import cn.edu.scut.suggestion.phrase.SemanticPhrase;

public class PhraseSuggest {

	public JSONObject getPhraseSuggest(JSONArray data,String query){
		Doc[] docs=convertToDoc(data).toArray(new Doc[0]);
		SemanticPhrase sp=new SemanticPhrase(query, docs);
		List<CandidatePhrase> candidatePhrases=sp.getCandidateSuggPhrase(query);
		for (CandidatePhrase candidatePhrase : candidatePhrases) {
			System.out.println(candidatePhrase.getLabel().getText()+"   "+candidatePhrase.getCandidateWord().getComunity());
		}	
		return candidateToJson(candidatePhrases);
	}
	
	private List<Doc> convertToDoc(JSONArray kapokDetails){
		List<Doc>  res=new ArrayList<Doc>();
		for (int i = 0; i < kapokDetails.size(); i++) {
			JSONObject hit=(JSONObject) kapokDetails.get(i);
			Doc doc=new Doc(i, hit.get("title").toString(), hit.get("summary").toString());
			res.add(doc);
		}
		return res;
	}
	
	private JSONObject candidateToJson(List<CandidatePhrase> candidatePhrases){
		HashMap<Integer, Vector<Integer>> alllist = new HashMap<Integer, Vector<Integer>>();
		for (int i = 0; i < candidatePhrases.size(); i++) {
			int comunity=candidatePhrases.get(i).getCandidateWord().getComunity();
			if (alllist.containsKey(comunity)) {
				alllist.get(comunity).add(i);
			} else {
				Vector<Integer> vi = new Vector<Integer>();
				vi.add(i);
				alllist.put(comunity, vi);
			}
		}

		JSONObject resJson=new JSONObject();
		JSONArray resArray=new JSONArray();
		for (Iterator<Integer> aIterator = alllist.keySet().iterator(); aIterator
				.hasNext();) {
			Integer key = aIterator.next();
			Vector<Integer> vlist = alllist.get(key);
			JSONArray clusterArray=new JSONArray();
			for (Integer integer : vlist) {
				if(candidatePhrases.get(integer).getLabel().getText().length()<22){
					System.out.print(candidatePhrases.get(integer).getLabel().getText());
					clusterArray.add(candidatePhrases.get(integer).getLabel().getText());
				}
			}
			resArray.add(clusterArray);
			System.out.println();
		}
		resJson.put("data", resArray);
		return resJson;
	}

}
